package com.wanmait.hotelManage.util;


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;



public class DBHelper {
	private DBHelper() {}
	private static DBHelper dbHelper=new DBHelper();
	public static DBHelper getDBHelper() {
		return dbHelper;
	}
	
	public Connection getConn() {
		Connection conn=null;
		try {
			Class.forName("com.mysql.cj.jdbc.Driver");
			
			String url="jdbc:mysql://localhost:3306/hotel_manage?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=Asia/Shanghai";
			String user="root";

			String paw="wanmait";

			conn=DriverManager.getConnection(url, user, paw);
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return conn;
	}
	public void close(ResultSet rs,PreparedStatement ps,Connection conn) {
		if(rs!=null) {
			try {
				rs.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			rs=null;
		}
		if(ps!=null) {
			try {
				ps.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			ps=null;
		}
		if(conn!=null) {
			try {
				conn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			conn=null;
		}
	}
	public int executeUpdate(String sql,Object... params)
	{
		int count=0;
		Connection conn = null;
		PreparedStatement ps = null;
		try {
			conn = DBHelper.getDBHelper().getConn();
			ps = conn.prepareStatement(sql);
			for(int i=0;i<params.length;i++)
			{
				ps.setObject(i+1, params[i]);
			}
			count = ps.executeUpdate();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		finally
		{
			DBHelper.getDBHelper().close(null, ps, conn);
		}
		return count;
	}
	
}
